<template>
  <div>
    <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
      <el-form-item prop="name" label="商品名称" :rules="formRules.name">
        <el-input
          class="form-item-width"
          v-model="formData.name"
          :minlength="2"
          :maxlength="100"
          clearable
          placeholder="请输入商品名称"
        ></el-input>
      </el-form-item>
      <el-form-item prop="sn" label="商品编号" :rules="formRules.sn">
        <el-input
          class="form-item-width"
          v-model="formData.sn"
          :minlength="2"
          :maxlength="100"
          clearable
          placeholder="请输入商品编号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="category_id" label="商品类别" :rules="formRules.category_id">
        <el-cascader
          class="form-item-width"
          v-model="formData.category_id"
          :options="categoryList"
          :props="{
            label: 'name',
            value: 'category_id',
            emitPath: false,
            checkStrictly: true
          }"
        />
      </el-form-item>
      <el-form-item prop="brand_id" label="品牌">
        <el-select class="form-item-width" v-model="formData.brand_id">
          <el-option
            v-for="item in brandList"
            :key="item.name"
            :label="item.name"
            :value="item.brand_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="market_enable" label="状态" :rules="formRules.market_enable">
        <el-radio-group v-model="formData.market_enable">
          <el-radio :label="true">上架</el-radio>
          <el-radio :label="false">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品图片" prop="image_list" :rules="formRules.image_list">
        <upload-sortable :goodsGalleryList="formData.image_list" @change="handlePictureChange"/>
      </el-form-item>
      <el-form-item label="商品视频" prop="video">
        <div v-if="formData.video" class="video">
          <video :src="formData.video" class="video-play" controls="controls">
            您的浏览器不支持视频播放
          </video>
          <i class="el-icon-close close" @click.stop="handleRemoveGoodsVideo"></i>
        </div>
        <el-upload
          :action="MixinUploadApi"
          :on-progress="uploadVideoProcess"
          :on-success="handleVideoSuccess"
          :on-error="handleVideoError"
          :before-upload="beforeUploadVideo"
          :show-file-list="false"
        >
          <i v-if="!formData.video && !video.flag" class="el-icon-plus video-uploader-icon"/>
          <el-progress
            v-if="video.flag"
            type="circle"
            :percentage="video.uploadPercent"
            style="margin-top:7px;"
          />
          <span v-if="video.errorTip" class="error" style="font-size: 12px;color:#f56c6c;">
            (视频上传失败，请重新上传！)
          </span>
          <div
            slot="tip"
            class="el-upload__tip"
            style="margin-top: -10px"
            v-if="!formData.video"
          >
            最多可以上传1个视频，建议大小10M，推荐格式mp4
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item prop="param_list" label="商品参数" v-if="collapseVal.length !== 0">
        <span v-if="collapseVal.length === 0">-</span>
        <el-collapse v-else :value="collapseVal">
          <el-collapse-item
            v-for="paramGroup in paramGroupList"
            v-if="paramGroup"
            :title="paramGroup.group_name"
            :key="paramGroup.group_id"
            :name="paramGroup.group_id"
          >
            <el-form-item
              v-for="(goods_param, index) in formData.param_list"
              v-if="goods_param && goods_param.group_id && paramGroup.group_id === goods_param.group_id"
              :key="index"
              :label="`${goods_param.param_name}：`"
              :prop="'param_list.' + index + '.param_value'"
              :rules="goods_param.required === 1 ? { required: true, message: `${goods_param.param_name}不能为空`, trigger: 'change' } : {}"
            >
              <el-input
                placeholder="长度为最多100个字符"
                maxlength="100"
                v-if="goods_param.param_type === 1"
                v-model="goods_param.param_value"
                class="form-item-width"
              />
              <el-select
                v-if="goods_param.param_type === 2"
                v-model="goods_param.param_value"
                placeholder="请选择"
                class="form-item-width"
              >
                <el-option
                  v-for="option in goods_param.option_list"
                  :key="option"
                  :label="option"
                  :value="option"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import * as API_Category from '@/api/category'
import * as API_BasicSetting from '@/api/basicSetting'
import * as API_goods from '@/api/goods'

export default {
  name: 'goodsEditFormBasicInfo',
  props: {
    propFormData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      // 表单数据
      formData: {
        image_list: [],
        video: '',
        market_enable: true
      },
      formRules: {
        name: [this.MixinRequired('请输入商品名称', 'change')],
        sn: [this.MixinRequired('请输入商品编号', 'change')],
        category_id: [this.MixinRequired('请选择商品类别', 'change')],
        image_list: [this.MixinRequired('请添加商品图片', 'change')],
        market_enable: [this.MixinRequired('请选择是否上架', 'change')]
      },
      // 分类列表
      categoryList: [],
      // 品牌列表
      brandList: [],
      video: {
        errorTip: false,
        flag: false,
        uploadPercent: 0
      },
      // 商品参数组列表
      paramGroupList: [],
      collapseVal: []
    }
  },
  mounted() {
    this.getCategoryAllChildren()
    this.getBrandAllList()
  },
  methods: {
    /** 获取分类 */
    getCategoryAllChildren() {
      API_Category.getCategoryAllChildren(0).then(response => {
        this.categoryList = response
      })
    },
    /** 获取品牌数据 */
    getBrandAllList() {
      API_BasicSetting.getBrandAllList().then(res => {
        this.brandList = res
      })
    },
    /** 查询商品参数 */
    async GET_GoodsParams() {
      this.paramGroupList = this.formData.id
        ? await API_goods.getEditGoodsParams(this.formData.category_id, this.formData.id)
        : await API_goods.getGoodsParams(this.formData.category_id)

      this.collapseVal = this.paramGroupList.map(key => key.group_id)
      this.formData.param_list = []
      this.paramGroupList.forEach(key => {
        if (key && key.params) {
          key.params.forEach(elem => {
            this.formData.param_list.push(elem)
          })
        }
      })
    },
    /** 商品图片发生改变 */
    handlePictureChange(fileList) {
      this.formData.image_list = fileList
    },
    /** 视频上传效验 */
    beforeUploadVideo(file) {
      const fileSize = file.size / 1024 / 1024 < 20
      if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) === -1) {
        this.$message.error('请上传正确的视频格式')
        return false
      }
      if (!fileSize) {
        this.$message.error('视频大小不能超过20MB')
        return false
      }
    },
    /** 视频上传时进度条 */
    uploadVideoProcess(event, file) {
      this.video.errorTip = false
      this.video.flag = true
      this.video.uploadPercent = file.percentage.toFixed(0) * 1
    },
    /** 视频上传成功 */
    handleVideoSuccess(res) {
      this.video.flag = false
      this.video.uploadPercent = 0
      this.formData.video = res.url
    },
    /** 视频上传失败 */
    handleVideoError() {
      this.video.errorTip = true
      this.video.flag = false
      this.video.uploadPercent = 0
      this.$message.error('上传失败!')
    },
    /** 移除上传的商品视频 */
    handleRemoveGoodsVideo() {
      this.video.flag = false
      this.formData.video = ''
    },
    /** 表单校验 */
    async validateForm() {
      try {
        await this.$refs.formRef.validate()
        // 校验通过更新数据
        Object.assign(this.propFormData, this.formData)
      } catch (e) {
        this.$message.error('【基本信息】不完善，请填写相关信息')
        this.$emit('updateActiveTab', 'basicInfo')
        // 截断父组件后面的代码
        throw e
      }
    }
  },
  watch: {
    'formData.category_id': {
      handler(newVal) {
        this.propFormData.category_id = newVal
        this.GET_GoodsParams()
      }
    },
    propFormData: {
      handler(newVal) {
        this.formData = newVal
        this.GET_GoodsParams()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item-width {
  width: 35%;
  min-width: 300px;
}
.form-item-width1 {
  width: 100%;
  min-width: 400px;
}
.video-uploader-icon {
  border: 1px dashed #d9d9d9;
  background-color: #fbfdff;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.video-uploader-icon:hover {
  border-color: #409eff;
}
.video {
  position: relative;
  width: 200px;
  height: 200px;
  .video-play {
    width: 200px;
    height: 200px;
    background: #000;
  }
  .close {
    position: absolute;
    right: 8px;
    top: 10px;
    font-size: 20px;
    color: #fff;
  }
}
/*折叠面板*/
.el-collapse-item {
  /deep/ .el-collapse-item__header {
    padding-left: 10px;
    font-size: 14px;
  }
  /deep/ .el-collapse-item__content {
    padding-top: 10px;
    padding-bottom: 0;
  }
}
</style>
